//
//  CAShapeLayer+WavePath.m
//  高仿暴走斗图
//
//  Created by key on 16/9/26.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "CAShapeLayer+WavePath.h"

@implementation CAShapeLayer (WavePath)

- (void)updateWavePathForParameter:(NSDictionary *)param wavePathcompleted:(void(^)(CGMutablePathRef path))completed
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGFloat waveCurrentY        = [param[@(kWavePathParameterTypeWaveCurrentY)] floatValue];
    CGFloat waveWidth           = [param[@(kWavePathParameterTypeWaveWidth)] floatValue];
    CGFloat waveCycle           = [param[@(kWavePathParameterTypeWaveCycle)] floatValue];
    CGFloat waveOffsetX         = [param[@(kWavePathParameterTypeWaveOffsetX)] floatValue];
    CGFloat waveInViewHeight    = [param[@(kWavePathParameterTypeWaveInViewHeight)] floatValue];
    CGFloat waveAmplitude       = [param[@(kWavePathParameterTypeWaveAmplitude)] floatValue];
    
    kWavePathFunctionType waveFunction        = (kWavePathFunctionType)[param[@(kWavePathParameterTypeWaveFunction)] integerValue];
    
    CGFloat y = waveCurrentY;
    CGPathMoveToPoint(path, nil, 0, y);
    for (CGFloat x = 0.0f; x <= waveWidth ; x++) {
        CGFloat functionValue = 0.0f;
        if (waveFunction == kWavePathFunctionTypeSin) {
            functionValue = sin(waveCycle * x + waveOffsetX);//正弦波浪公式
        } else if (waveFunction == kWavePathFunctionTypeCos) {
            functionValue = cos(waveCycle * x + waveOffsetX);//余弦波浪公式
        }
        y = waveAmplitude * functionValue + waveCurrentY;
        CGPathAddLineToPoint(path, nil, x, y);
    }
    
    CGPathAddLineToPoint(path, nil, waveWidth, waveInViewHeight);
    CGPathAddLineToPoint(path, nil, 0, waveInViewHeight);
    CGPathCloseSubpath(path);
    
    self.path = path;
    if (completed) {
        completed(path);
    }
    CGPathRelease(path);
}

@end
